import {
  Dataset,
  FAKE_DATASETS,
  deleteDataset,
  getDatasetList,
} from "@/external-api";
import styles from "@/styles/DataManage.module.css";
import { Button, Popconfirm, Table, TableProps, message } from "antd";
import Link from "next/link";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";

const NORMAL_COLUMNS: TableProps["columns"] = [
  {
    title: "序号",
    render: (text, record, index) => `${index + 1}`,
    key: "index",
    align: "center",
    width: "5%",
  },
  {
    title: "样本集",
    render: (text, record) => (
      <Link href={`data-manage/${record.id}`}>{text}</Link>
    ),
    dataIndex: "name",
    key: "name",
    align: "center",
    width: "15%",
  },
  {
    title: "数据均衡性",
    dataIndex: "dataBalance",
    key: "dataBalance",
    align: "center",
    width: "15%",
  },
  {
    title: "类别均衡性",
    dataIndex: "classBalance",
    key: "classBalance",
    align: "center",
    width: "15%",
  },
  {
    title: "纹理均衡性",
    dataIndex: "textureBalance",
    key: "textureBalance",
    align: "center",
    width: "15%",
  },
  {
    title: "修改时间",
    dataIndex: "updateTime",
    key: "updateTime",
    align: "center",
    width: "20%",
  },
];

const TableArea = ({ type }: { type: string }) => {
  const router = useRouter();
  const [dataSource, setDataSource] = useState<Dataset[]>([]);

  // 获取样本集数据
  useEffect(() => {
    getDatasetList(type).then((dataList) => setDataSource(dataList));
  }, [type]);

  // 删除样本集
  const handleDelete = (id: number) => {
    return () => {
      deleteDataset(id).then(() => {
        getDatasetList(type).then((dataList) => setDataSource(dataList));
      });
    };
  };

  // 定义表格操作
  const columns: TableProps["columns"] = [
    ...NORMAL_COLUMNS,
    {
      title: "操作",
      key: "action",
      render: (text, record) => (
        <>
          <Button
            type="text"
            size="small"
            style={{ color: "var(--primary)" }}
            onClick={() => {
              router.push(`data-manage/${record.id}`);
            }}
          >
            查看
          </Button>
          <Popconfirm
            title="删除确认"
            description="样本集删除后无法恢复，是否确认？"
            onConfirm={handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="text"
              size="small"
              danger
              style={{ color: "var(--danger)" }}
            >
              删除
            </Button>
          </Popconfirm>
        </>
      ),
      align: "center",
      width: "15%",
    },
  ];

  return (
    <div className={styles.tableArea}>
      <Table
        style={{ width: "90%" }}
        columns={columns}
        dataSource={dataSource}
        rowKey="id"
        loading={false}
      />
    </div>
  );
};

export default TableArea;
